package com.roger.myHome.aspect;


import com.roger.myHome.entity.LoginUser;
import com.roger.myHome.util.UserHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Slf4j
@Component
@Aspect
@Order(-100)
public class AuthAspect {

    @Resource
    private UserHelper userHelper;

    @Around("@annotation(com.roger.myHome.aspect.AuthAnnotation)")
    public Object  doBeforeMethod(ProceedingJoinPoint joinPoint) throws Throwable{
        //String method = joinPoint.getSignature().getName();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        LoginUser user = userHelper.getLoginUser(request);
        String url = request.getRequestURL().toString();
        log.info("[{}]请求的URL:[{}]", user.getId(),url);

        try {
            if (user.getId() != 1) {
                throw new RuntimeException("没有权限访问URL" + request.getRequestURL());
            }
            return joinPoint.proceed();
        } catch (Exception e){
            log.error("没有权限访问URL:[{}]", request.getRequestURL());

            return "没有权限访问";
        }

    }


}
